package com.xzh.controller;

import com.xzh.entity.User;
import com.xzh.service.UserService;
import com.xzh.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/userLogin")
    public ModelAndView userLogin(User user){
        User u=userService.userLogin(user);
        ModelAndView mv=new ModelAndView();
        if (u!=null){
            mv.setViewName("forward:getUsers.do");
            mv.addObject("user", u);
        }else {
            mv.setViewName("reg");
        }
        return mv;
    }

    @RequestMapping("/getUsers")
    public ModelAndView getUsers(@RequestParam(defaultValue = "1", required = true) int pageIndex) {
        ModelAndView mv = new ModelAndView();
        List<User> list = userService.getPageUsers(PageUtil.PAGE_SIZE, pageIndex);
        int total=userService.getTotal();
        int totalPage=PageUtil.getTotalPage(total,PageUtil.PAGE_SIZE);
        mv.addObject("list", list);
        mv.addObject("pageIndex",pageIndex);
        mv.addObject("totalPage",totalPage);
        mv.setViewName("main");
        return mv;
    }

    @RequestMapping("/up")
    public String fileUpload(MultipartFile file, HttpServletRequest request)throws IOException {
        //获取完整路径
        String realPath=request.getSession().getServletContext().getRealPath("/upload");
        //创建文件夹
        File f=new File(realPath);
        if (!f.exists()){
            f.mkdir();
        }
        //
        String fileName=file.getOriginalFilename();
        fileName= UUID.randomUUID()+"_"+fileName;
        //
        File newFile=new File(f,fileName);
        //
        file.transferTo(newFile);
        return "index";


    }

}
